/**Created by the LayaAirIDE*/
module view{
	export class GameScene extends ui.GameSceneUI{
		stageNum: number = 1
		waveNum: number = 0
		monsters: Monster[] = []
		constructor(){
			super();

			this._init();
		}

		_init(): void {
			this.soundBtn.on("click", this, this.soundBtnClick, [0])
			this.exitBtn.on("click", this, this.gameExit, [0]) 
			this.updateSoundBtn(!SoundPlayer.Instance.mute)
		}

		soundBtnClick(): void {
			this.updateSoundBtn(!this.soundBtn.selected)
			SoundPlayer.Instance.setMute(!this.soundBtn.selected)
		}

		updateSoundBtn(selected: boolean): void {
			if (selected) {
				this.soundBtn.skin = "images/button_sound_off.png"
			}else {
				this.soundBtn.skin = "images/button_sound_on.png"
			}

			this.soundBtn.selected = selected
		}

		//创建关卡布局
		makeSceneUI(stageNum: number): void {
			this.stageNum = stageNum
			this.waveNum = 0

			this.makeMonstor()
			Laya.timer.loop(3000, this, this.mainRunloop, null, false)
			Laya.timer.loop(100, this, this.moveRunloop, null, false)
		}

		//控制精灵移动
		makeMonstor(): void {
			// 每次创建5 个怪物
			var x: number = GetRandomNum(1, 5)
			for (var index = 0; index < 5; index++) {
				var monster: Monster = new Monster()
				monster.setWave(this.waveNum)
				monster.mosterx = x
				this.stageBg.addChild(monster)
				monster.pos((-100 * index), 200)
				this.monsters.push(monster)
			}

			//更新波数信息
			this.waveNum++
			this.waveLabel.text = "wave: " + this.waveNum.toString() + "/5"
		}

		//游戏主循环
		mainRunloop(): void {
			if (this.waveNum >= 5) {
				this.gameExit()
				Laya.timer.clear(this, this.mainRunloop)
				Laya.timer.clear(this, this.moveRunloop)
				return
			}
			if (this.monsters.length > 3) {
				return
			}

			this.makeMonstor()
		}

		moveRunloop(): void {
			for (var index = 0; index < this.monsters.length; index++) {
				var element = this.monsters[index];
				element.move()

				if (element.life <= 0) {
					element.die()
					this.monsters.splice(index, 1)
				}
			}
		}

		gameExit(): void {
			Laya.timer.clear(this, this.mainRunloop)
			Laya.timer.clear(this, this.moveRunloop)

			var exitDialog: view.GameExitDialog = new view.GameExitDialog()
			exitDialog.zOrder = 100
			
			this.addChild(exitDialog)
			exitDialog.zOrder = 10000

			exitDialog.confirmBtn.on("click", this, () => {
				game.gameExit()
				this.removeSelf()
				this.destroy()
				exitDialog.removeSelf()
				exitDialog.destroy()
			}, [0])

			exitDialog.cancelBtn.on("click", this, () => {
				Laya.timer.loop(3000, this, this.mainRunloop, null, false)
				Laya.timer.loop(100, this, this.moveRunloop, null, false)
				exitDialog.removeSelf()
				exitDialog.destroy()
			}, [0])
		}
	}
}